﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using kwzx.Common;
using kwzx.Data;
using System.IO;
using System.Data.Objects;

namespace kwzx
{
    public partial class frmScmCard : Form
    {
        public frmScmCard()
        {
            InitializeComponent();
        }



        private string _sendCardURL = System.Configuration.ConfigurationSettings.AppSettings["ScmSendCardURL"];
        private string _initCardURL = System.Configuration.ConfigurationSettings.AppSettings["InitCardURL"];
        private string _comMsgURL = System.Configuration.ConfigurationSettings.AppSettings["ScmComURL"];
        private void frmScmCard_Load(object sender, EventArgs e)
        {
            InitTree();
            this.user_cardDataGridView.MultiSelect = false;
        }

        #region 加载树
        private void InitTree()
        {
            scm_mainEntities scm = new scm_mainEntities();
            List<dt_dep> deps = scm.dt_dep.OrderBy(a => a.dep_order).ToList();
            var depmodel = deps.Where(a => a.dep_no_add == "0").FirstOrDefault();
            if (depmodel != null)
            {

                TreeNode tn = new TreeNode();
                tn.SelectedImageIndex = 3;
                tn.Text = depmodel.dep_name;
                tn.Name = depmodel.dep_no_add;
                treeView1.Nodes.Add(tn);
                tn.ImageIndex = 0;
                PrcFillTreeNodes(deps, depmodel, tn);
            }
            scm.Dispose();
        }

        /// <summary>
        /// 填充机构跟树节点
        /// </summary>
        /// <param name="ajg1"></param>
        /// <param name="ax"></param>
        /// <param name="tr"></param>
        private void PrcFillTreeNodes(List<dt_dep> ajg1, dt_dep ax, TreeNode tr)
        {
            var r2 = from a in ajg1 where a.dep_parent == ax.dep_serial select a;
            foreach (dt_dep item in r2.ToList())
            {
                TreeNode node = tr.Nodes.Add(item.dep_name);
                node.Name = item.dep_no_add.ToString();
                node.SelectedImageIndex = 3;
                node.ImageIndex = 1;
                PrcFillTreeNodes(ajg1, item, node);
            }

        }
        #endregion





        private List<dt_user> users = new List<dt_user>();
        private string depid = "1";

        /// <summary>
        /// 树选中一结点时，在右侧的GridView中关联显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                depid = e.Node.Name.ToString();

                QueryCommon("", "", "");

            }
        }


        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            QueryCommon("", "", "");

        }
        private void btnSearch_Click(object sender, EventArgs e)
        {

            QueryCommon(txtUserName.Text, txtCardNO.Text, txtUserIdentity.Text);
        }


        private void QueryCommon(string txtuserName, string cardNo, string userIdentity)
        {
            scm_mainEntities scm = new scm_mainEntities();
            users = scm.dt_user.Where(a => a.dep_no_add == depid).ToList();
            scm.Dispose();

            if (this.radioButton1.Checked == true)
            {
                users = (from a in users where a.user_card == null || a.user_card=="" select a ).ToList();

            }
            else
            {
                users = users.Where(a => a.user_card != null ).ToList();
            }
            if (!string.IsNullOrWhiteSpace(txtuserName))
            {

                users = users.Where(a => a.user_lname.Contains(txtUserName.Text)).ToList();
            }
            if (!string.IsNullOrWhiteSpace(cardNo))
            {

                users = users.Where(a => a.user_card.Contains(txtCardNO.Text)).ToList();
            }
            if (!string.IsNullOrWhiteSpace(userIdentity))
            {

                users = users.Where(a => a.user_id.Contains(txtUserIdentity.Text)).ToList();
            }
            this.dtuserBindingSource.DataSource = users;

            if (users.Count() < 1)
            {

                SetControlValue();
            }
        }


        //给控件赋值
        private void vusercardBindingSource_PositionChanged(object sender, EventArgs e)
        {
            if (this.dtuserBindingSource.Current != null)
            {
                dt_user user = (dtuserBindingSource.Current) as dt_user;
                if (user != null)
                {
                    HXYKTEntities db = new HXYKTEntities();
                    var model = db.T_USER.Where(a => a.rybh == user.user_no).FirstOrDefault();
                    if (model != null)
                    {
                        rybhTextBox.Text = model.rybh == null ? "" : model.rybh;
                        zSXMTextBox.Text = model.ZSXM;
                        dEPT_idTextBox.Text = GetDeptName(model.DEPT_id);
                        uBYTextBox.Text = model.UBY;
                        gzTextBox.Text = GetDETAIL(model.gz);
                        xBTextBox.Text = model.XB == null ? "男" : model.XB;
                        zWTextBox.Text = model.ZW == null ? "" : model.ZW;
                        dHTextBox.Text = model.DH;
                        sfzhTextBox.Text = model.sfzh;
                        dZTextBox.Text = model.DZ;
                        //    rY_IDTextBox.Text = GetDETAIL(model.RY_ID);
                        if (model.ZP != null)
                        {
                            //~/admin/ftp/DBPersonImg/吴恩来622101196002040310.jpg
                            string photoPath = model.ZP;
                            int supNum = photoPath.LastIndexOf("ftp") + 4;  //最后一个出现 在加上ftp/

                            photoPath = photoPath.Substring(supNum, photoPath.Length - supNum);
                            int userImginfo = photoPath.IndexOf("/") + 1;
                            string zpName = photoPath.Substring(userImginfo, photoPath.Length - userImginfo);
                            string kkzp = FileTran.DownloadFile(SPicUtils.path, zpName, photoPath);
                            this.pictureBox1.Image = SPicUtils.PicConvert(kkzp);
                        }
                        db.Dispose();
                    }
                    else
                    {
                        SetControlValue();
                    }
                }
            }
        }


        #region  获得一些常用的字段值

        //获得职称，工种等
        public string GetDETAIL(int? detailID)
        {
            string result = "";
            using (HXYKTEntities db = new HXYKTEntities())
            {
                var modle = (db.X_CS_DETAIL.Where(a => a.DETAIL_ID == detailID).FirstOrDefault());
                if (modle != null || modle.MC != "")
                {
                    result = modle.MC;
                }

            }
            return result;
        }

        //获得人员类型
        public string GetUserType(int? typeID)
        {
            string result = "";
            using (HXYKTEntities db = new HXYKTEntities())
            {
                var modle = (db.CD_UserType.Where(a => a.RY_ID == typeID).FirstOrDefault());
                if (modle != null || modle.RY_Name != "")
                {
                    result = modle.RY_Name;
                }

            }
            return result;
        }

        /// <summary>
        /// 获得部门名称
        /// </summary>
        /// <param name="deptID"></param>
        /// <returns></returns>
        public string GetDeptName(int? deptID)
        {
            string result = "";
            using (HXYKTEntities db = new HXYKTEntities())
            {
                var modle = (db.T_BM.Where(a => a.DEPT_id == deptID).FirstOrDefault());
                if (modle != null || modle.BMMC != "")
                {
                    result = modle.BMMC;
                }

            }
            return result;
        }
        #endregion


        #region scm 操作
        //scm 初始化
        private void btnInitCard_Click(object sender, EventArgs e)
        {

            frmScmShow frm = new frmScmShow();
            frm.uri = new Uri("http://localhost:205/login_auto.asp?user=admin&u_1=m9041");
            frm.Text = "消费卡片初始化";
            frm.Show();

        }

        //scm写卡
        private void btnScmWrite_Click(object sender, EventArgs e)
        {
            dt_user user = (dtuserBindingSource.Current) as dt_user;
            if (dtuserBindingSource.Current != null  && user != null)
            {

                string name = user.user_lname;
  
                frmScmShow frm = new frmScmShow();
                frm.myevent += new frmScmShow.mydelegate(givevalue);
                string str = _sendCardURL + "&u_1=m9002&u_2=" + user.user_serial;
                frm.uri = new Uri(str);
                frm.Text = "消费" + name + "写卡";
                frm.Show();
    
            }
        }



        public void givevalue(bool text) //用于修改label的方法
        {
            QueryCommon("", "", "");
        }


        //设备通讯
        private void btnDataCom_Click(object sender, EventArgs e)
        {
            // frm.uri = new Uri("http://localhost:202/login_auto.asp?user=admin&u_1=m4072");
            frmScmShow frm = new frmScmShow();
            string str = _comMsgURL + "&u_1=m4072";
            frm.uri = new Uri(str);
            frm.Text = "消费数据下发";
            frm.Show();
        }


        //挂失
        private void btnLoss_Click(object sender, EventArgs e)
        {
            if (dtuserBindingSource.Current != null)
            {
                string user_id = ((DataRowView)dtuserBindingSource.Current)["user_serial"].ToString();
                HXYKTEntities db = new HXYKTEntities();
                var model = db.T_USER.Where(a => a.rybh == user_id).FirstOrDefault();
                if (model != null)
                {
                    //根据工号查找 工号在平台和scm有且唯一
                    string personNum = model.rybh.ToString();
                    scm_mainEntities scm = new scm_mainEntities();
                    var scmModel = scm.dt_user.Where(a => a.user_no == personNum).FirstOrDefault();
                    if (scmModel != null)
                    {
                        //人员挂失平台代码
                        CallProc call = new CallProc();
                        int result = call.UserLossEx(scmModel.user_serial.ToString());
                        MessageBox.Show("挂失成功");
                    }
                }
                db.Dispose();
            }
        }
        #endregion


        private void frmScmCard_FormClosed(object sender, FormClosedEventArgs e)
        {
            GC.Collect();
            //删除下载的图片

            string fullImg = AppDomain.CurrentDomain.BaseDirectory + "img";
            DirectoryInfo fr = new DirectoryInfo(fullImg);
            foreach (var item in fr.GetFiles())
            {
                item.Delete();
            }
        }



        private void SetControlValue()
        {
            pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
            foreach (var item in this.groupBox2.Controls)
            {
                TextBox text = item as TextBox;
                if (text != null)
                {
                    text.Text = "";
                }

            }
        }














    }


}
